package cn.source.framework.web.service;

import cn.source.common.constant.Constants;
import cn.source.common.core.domain.AjaxResult;
import cn.source.common.core.domain.entity.SysUser;
import cn.source.common.core.domain.model.LoginUser;
import cn.source.common.core.redis.RedisCache;
import cn.source.common.exception.ServiceException;
import cn.source.common.exception.user.CaptchaException;
import cn.source.common.exception.user.CaptchaExpireException;
import cn.source.common.exception.user.UserPasswordNotMatchException;
import cn.source.common.utils.DateUtils;
import cn.source.common.utils.MessageUtils;
import cn.source.common.utils.ServletUtils;
import cn.source.common.utils.StringUtils;
import cn.source.common.utils.ip.IpUtils;
import cn.source.framework.manager.AsyncManager;
import cn.source.framework.manager.factory.AsyncFactory;
import cn.source.system.domain.SysCompany;
import cn.source.system.service.ISysCompanyService;
import cn.source.system.service.ISysConfigService;
import cn.source.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired private TokenService tokenService;

    @Resource private AuthenticationManager authenticationManager;

    @Autowired private RedisCache redisCache;

    @Autowired private ISysUserService userService;

    @Autowired private ISysConfigService configService;

    @Autowired private ISysCompanyService companyService;

    // 是否允许账户多终端同时登录（true允许 false不允许）
    @Value("${token.soloLogin}")
    private boolean soloLogin;

    /**
     * 三方登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public AjaxResult thirdLogin(String username, String password) {
        AjaxResult ajax = AjaxResult.success();
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication =
                    authenticationManager.authenticate(
                            new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me()
                        .execute(
                                AsyncFactory.recordLogininfor(
                                        username,
                                        Constants.LOGIN_FAIL,
                                        MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me()
                        .execute(
                                AsyncFactory.recordLogininfor(
                                        username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me()
                .execute(
                        AsyncFactory.recordLogininfor(
                                username,
                                Constants.LOGIN_SUCCESS,
                                MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        String token = tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, token);
        ajax.put("loginUser", loginUser);
        return ajax;
    }

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication =
                    authenticationManager.authenticate(
                            new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me()
                        .execute(
                                AsyncFactory.recordLogininfor(
                                        username,
                                        Constants.LOGIN_FAIL,
                                        MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me()
                        .execute(
                                AsyncFactory.recordLogininfor(
                                        username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        // 异步写入日志
        AsyncManager.me()
                .execute(
                        AsyncFactory.recordLogininfor(
                                username,
                                Constants.LOGIN_SUCCESS,
                                MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // // 校验授权，7天以内给于提醒
        // if (StringUtils.isNotNull(loginUser.getUser().getCompanyId())) {
        //     SysCompany company =
        //             companyService.selectSysCompanyById(loginUser.getUser().getCompanyId());
        //     Date effectiveEndDate =
        //             StringUtils.isNull(company.getEffectiveEndDate())
        //                     ? DateUtils.getNowDate()
        //                     : company.getEffectiveEndDate();
        //     if (company.getStatus().equals(Constants.NO)
        //             || effectiveEndDate.compareTo(DateUtils.getNowDate()) <= 0) {
        //         // 如果已经过了有效期，则提示授权已到期
        //         throw new ServiceException("授权已到期，请联系管理员续期");
        //     }
        // }
        if (!soloLogin) {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey)) {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }
        // 记录登录信息
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me()
                    .execute(
                            AsyncFactory.recordLogininfor(
                                    username,
                                    Constants.LOGIN_FAIL,
                                    MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me()
                    .execute(
                            AsyncFactory.recordLogininfor(
                                    username,
                                    Constants.LOGIN_FAIL,
                                    MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
